package com.shangye.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private static MimetypesFileTypeMap mime = new MimetypesFileTypeMap();

    private Socket socket;
    private int statusCode = 200;
    private String statusReason = "OK";
    private File contentFile;

    private Map<String, String> headers = new HashMap<>();

    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }

    public void respose() throws IOException {

        sendStatusLine();
        sendHeaders();
        sendContnt();
    }

    private void sendStatusLine() throws IOException {

        //发送状态行
        //HTTP/1.1 200 OK(CRLF)
        println("HTTP/1.1 " + statusCode + " " + statusReason);
    }

    private void sendHeaders() throws IOException {
        //发送响应头
        Set<Map.Entry<String, String>> entries = headers.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            println(entry.getKey() + entry.getValue());
        }
        //单独发送回车+换行表达响应头发送完毕
        println("");

    }

    private void sendContnt() throws IOException {
        OutputStream out = socket.getOutputStream();
        try (
                FileInputStream fis = new FileInputStream(contentFile);
        ) {
            byte[] data = new byte[1024 * 10];
            int len;
            while ((len = fis.read(data)) != -1) {
                out.write(data, 0, len);
            }
        }
    }

    private void println(String line) throws IOException {

        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }

    public void addHeaders(String key,String value){
        headers.put(key,value);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        addHeaders("Content-Type: ",mime.getContentType(contentFile));
        addHeaders("Content-Length: ",contentFile.length()+"");
    }
}
